<?php


// 购物车
namespace app\controller\v1;


use app\model\CartProducts;
use app\model\Products;
use app\model\ProductSkus;
use app\model\ProductDescriptions;
use app\model\Sellers;
use app\service\CartService;
use think\Request;

class CartController extends BaseAPIController
{
    // 添加购物车
    public function addCart(Request $request)
    {
        $userId = $this->userService->getCurrentUserId();
        $productId = (int)$this->request->post('product_id');
        $quantity = (int)$this->request->post('quantity');
        $skuId = (string)$this->request->post('sku_id');
        $cart = CartProducts::where('customer_id', $userId)
            ->where('product_id', $productId)
            ->where('product_sku', $skuId)
            ->find();
        if ($cart) {
            $cart->quantity += $quantity;
            $cart->selected = 1;
            $cart->updated_at = date('Y-m-d H:i:s');
            $cart->save();
            return $this->success([], '已加入购物车');
        }
        $res = CartProducts::create([
            'customer_id' => $userId,
            'selected' => 1,
            'product_id' => $productId,
            'product_sku' => $skuId,
            'quantity' => $quantity,
            'created_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
        ]);
        if (!$res) {
            return $this->error('加入购物失败');
        }
        return $this->success([], '已加入购物车');
    }


    //获取选中的购物车产品
    public function getCartSelected(Request $request)
    {
        $userId = $this->userService->getCurrentUserId();

        // 查询购物车产品并关联产品信息、SKU信息、产品描述
        $cartItems = CartProducts::alias('cp')
            ->leftJoin('products p', 'cp.product_id = p.id')
            ->leftJoin('product_skus ps', 'cp.product_sku = ps.id')
            ->leftJoin('product_descriptions pd', 'p.id = pd.product_id')
            ->where('cp.customer_id', $userId)
            ->where('cp.selected', 1)
            ->where('p.active', 1) // 只查询启用的产品
            ->where('pd.locale', 'zh_cn') // 中文描述
            ->field([
                'cp.id as cart_id',
                'cp.product_id',
                'cp.product_sku',
                'cp.quantity',
                'p.images as product_images',
                'p.price as product_price',
                'p.variables as product_variables',
                'pd.name as product_name',
                'ps.price as sku_price',
                'ps.origin_price as sku_origin_price',
                'ps.variants as sku_variants',
                'ps.images as sku_images'
            ])
            ->select()
            ->toArray();

        if (empty($cartItems)) {
            return $this->success([
                'items' => [],
                'total_amount' => 0,
                'total_quantity' => 0
            ], '购物车为空');
        }

        $totalAmount = 0;
        $totalQuantity = 0;
        $formattedItems = [];

        foreach ($cartItems as $item) {
            // 处理产品图片
            $productImages = json_decode($item['product_images'], true) ?: [];
            $skuImages = empty($item['sku_images']) ? [] : json_decode($item['sku_images'], true);
            $images = !empty($skuImages) ? $skuImages : $productImages;
            $mainImage = !empty($images) ? $images[0] : '';
            $mainImage = (env('IMAGE_URL') . $mainImage);
            // 处理SKU规格
            // 数据["0"]
            $skuVariants = empty($item['sku_variants']) ? [] : json_decode($item['sku_variants'], true);
            // 数据[{"name": {"en": "color", "zh_cn": "颜色"}, "values": [{"name": {"en": "colro", "zh_cn": "蓝色"}, "image": ""}], "isImage": false}]
            $productVariants = empty($item['product_variables']) ? [] : json_decode($item['product_variables'], true);
            $variantText = '';
            $variantDetails = [];
            // 根据SKU variants索引获取对应的产品规格信息
            if (!empty($skuVariants) && !empty($productVariants)) {
                list($variantText, $variantDetails) = getSkuVariant($skuVariants, $productVariants);
            }
            // 使用SKU价格，如果没有则使用产品价格
            $price = $item['sku_price'] > 0 ? $item['sku_price'] : $item['product_price'];
            $originPrice = $item['sku_origin_price'] > 0 ? $item['sku_origin_price'] : $price;

            // 计算小计
            $subtotal = $price * $item['quantity'];
            $totalAmount += $subtotal;
            $totalQuantity += $item['quantity'];
            $formattedItems[] = [
                'cart_id' => $item['cart_id'],
                'product_id' => $item['product_id'],
                'product_sku_id' => $item['product_sku'],
                'product_name' => $item['product_name'] ?: '未知商品',
                'product_image' => $mainImage,
                'sku_name' => $variantText,
                'sku_list' => $variantDetails,
                'price' => round($price, 2),
                'origin_price' => round($originPrice, 2),
                'quantity' => $item['quantity'],
                'subtotal' => round($subtotal, 2),
            ];
        }

        return $this->success([
            'items' => $formattedItems,
            'total_amount' => round($totalAmount, 2),
            'total_quantity' => $totalQuantity
        ], '获取成功');
    }


    // 购物车获取

    public function getCartList(Request $request)
    {
        $userId = $this->userService->getCurrentUserId();
        $cartService = new CartService($userId);
        $cartItems = $cartService->getCartList();
        return $this->success($cartItems, '获取成功');
    }

    // 自增购物车数量
    public function increment(Request $request)
    {
        try {
            $userId = $this->userService->getCurrentUserId();
            $cartService = new CartService($userId);
            $cartItems = $cartService->increment($request->get(''));
            return $this->success($cartItems, '增加成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage(),400);
        }
    }

    //减少购物车产品数量
    public function decrement(Request $request)
    {
        try {
            $userId = $this->userService->getCurrentUserId();
            $cartService = new CartService($userId);
            $cartItems = $cartService->decrement($request->get(''));
            return $this->success($cartItems, '减少成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage(),400);
        }
    }
    // 删除购物车产品
    public function deleteCartItem(Request $request)
    {
        try {
            $userId = $this->userService->getCurrentUserId();
            $cartService = new CartService($userId);
            $cartItems = $cartService->deleteCartItem($request->get('ids'));
            return $this->success($cartItems, '删除成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage(),400);
        }
    }

    // 清空用户购物车
    public function clearCart(Request $request)
    {
        try {
            $userId = $this->userService->getCurrentUserId();
            $cartService = new CartService($userId);
            $cartItems = $cartService->clearCart();
            return $this->success($cartItems, '清空成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage(),400);
        }
    }

    //购物车选中
    public function selectedCartItem(Request $request)
    {
        try {
            $userId = $this->userService->getCurrentUserId();
            $cartService = new CartService($userId);
            $cartItems = $cartService->selectedCartItem($request->get('ids'));
            return $this->success($cartItems, '选中成功');
        } catch (\Exception $e) {
            return $this->error($e->getMessage(),400);
        }
    }
}
